/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ru.miit.elearning.vtutor.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import ru.miit.elearning.vtutor.check.ZOSCheckServiceClient;
import ru.miit.elearning.vtutor.check.ZOSChecker;
import ru.miit.elearning.vtutor.wsclient.VlStudent;
import ru.miit.elearning.vtutor.wsclient.ZosCheckBundle;

/**
 *
 * @author Cyclone
 */
public class CheckServlet extends HttpServlet {

    //@WebServiceRef(wsdlLocation = "WEB-INF/wsdl/localhost_8080/Elearning/VirtualTutorIBMService.wsdl")
    //private VirtualTutorIBMService service;
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            long start = System.currentTimeMillis();
            int courseId = Integer.parseInt(request.getParameter("courseId"));
            ZosCheckBundle checkBundle = ZOSCheckServiceClient.getZosCheckBundle(courseId, request.getRemoteUser());
            List<VlStudent> studentList = checkBundle.getStudentList();
            String checkStudentsMessage = "";

            ListIterator<VlStudent> iter = studentList.listIterator();
            for (Iterator<VlStudent> it = iter; it.hasNext();) {
                VlStudent student = it.next();
                String zosHome = null;
                if((zosHome = student.getZOSHomeFolder()) == null || zosHome.length() < 1) {
                    checkStudentsMessage += "  Студент "+student.getName()+": не задан домашний каталог z/OS.\n";
                    iter.remove();
                }

            }

            ZOSChecker checker = new ZOSChecker(courseId, checkBundle.getFtpFullUrl());
            String checkMessage = checker.checkLabsByStudents(checkBundle.getLabList(), checkBundle.getStudentList(), new HashSet(checkBundle.getApprovedSet()));
//System.out.println(System.currentTimeMillis() - start);
            float time = (System.currentTimeMillis() - start) / 1000f;

            StringBuilder ajaxResponse = new StringBuilder(String.format("%.2f", time));
            if(checkStudentsMessage.length() > 0 || checkMessage.length() > 0) {
                ajaxResponse.append("msg:").append(checkStudentsMessage).append(checkMessage);
            }
//            out.print(String.format("%.2f", time)+(checkStudentsMessage != null ? "msg:"+checkStudentsMessage : ""));
            
            out.print(ajaxResponse.toString());

        } catch (IOException e) {
            //out.print("Ошибка подключения к FTP серверу<br/>");
            //out.print(e.getMessage());
            e.printStackTrace();
            out.print("msg:  Ошибка подключения к FTP серверу.\n");
            //response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } catch (Exception e) {

            //out.print("Произошла непредвиденная ошибка<br/>");
            //out.print(e.getMessage());
            Logger.getLogger(CheckServlet.class.getName()).log(Level.SEVERE, null, e);
            e.printStackTrace();
            //out.print("checkStudentsMessage:Непредвиденная ошибка.\n");
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
